﻿using System;
using System.Web;
using monit.util.logger;
using System.IO;
namespace SIS_Wcf_Server
{
    public class IISLoggingHandler : IHttpModule
    {


        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        private void writelog(string s)
        {
            LogObjectServer.getServer().CurrentLogger.DoLog( LogObjectServer.getServer().LogFactory.createLogEntry( s, LogSeverity.INFO, "SisRestServer" )); 
        }



        #region IHttpModule Members

        void IHttpModule.Dispose()
        {
            throw new NotImplementedException();
        }

        void IHttpModule.Init(HttpApplication context)
        {
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        private string StreamToString(Stream stream)
        {
            StreamReader sr = new StreamReader(stream);
            string r = sr.ReadToEnd();
            sr.Close();
            return r;
            
        }


        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest request = app.Context.Request;
            writelog( request.HttpMethod + " " + request.RawUrl.ToString() + " " + request.ServerVariables["SERVER_PROTOCOL"] );
            foreach ( string s in request.Headers.AllKeys )
            {
                writelog( s + "=" + request.Headers[ s ] );
            }
            long currentpos = request.InputStream.Position;

            request.InputStream.Position = 0;
            writelog("Body: " + StreamToString(request.InputStream));
            request.InputStream.Position = currentpos;
        }

        #endregion
    }
}
